package com.geeklan.base.base;

import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.viewbinding.ViewBinding;

import com.geeklan.base.network.NetworkMonitor;
import com.geeklan.base.widget.MyProgressDialog;

import org.greenrobot.eventbus.EventBus;

public abstract class BaseFragment<T extends ViewBinding> extends Fragment implements NetworkMonitor.NetworkCallBack {
    protected T mBinding;
    protected abstract T initBinding();
    protected abstract void initData();
    protected abstract void initView();
    public boolean isRegisterEvent(){
        return false;
    }
    public boolean isRegisterNetwork(){
        return false;
    }
    private NetworkMonitor mNetworkMonitor;
    private MyProgressDialog progressDialog;
    public Context mContext;

    public static final int PERMISSION_REQ_ID = 22;
    private View view;
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if(view == null) {
            mBinding = initBinding();
            view = mBinding.getRoot();
            mContext = getContext();
            progressDialog = new MyProgressDialog(mContext);
            if (isRegisterEvent()) {
                EventBus.getDefault().register(this);
            }
            if (isRegisterNetwork()) {
                mNetworkMonitor = new NetworkMonitor(mContext, this);
                mNetworkMonitor.startNetworkMonitoring();
            }

            initData();
            initView();
        }
        return view;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if(isRegisterEvent()){
            EventBus.getDefault().unregister(this);
        }
        if(isRegisterNetwork()) {
            if (mNetworkMonitor != null) {
                mNetworkMonitor.stopNetworkMonitoring();
            }
        }
    }

    public void loading(){
        progressDialog.show();
    }

    public void dismiss(){
        progressDialog.dismiss();
    }
}
